/*
 *所有关于material_plan_xie类的业务代码应在此处编写
*可使用repository.调用常用方法，获取EF/Dapper等信息
*如果需要事务请使用repository.DbContextBeginTransaction
*也可使用DBServerProvider.手动获取数据库相关信息
*用户信息、权限、角色等使用UserContext.Current操作
*material_plan_xieService对增、删、改查、导入、导出、审核业务代码扩展参照ServiceFunFilter
*/
using DGZImp.Core.BaseProvider;
using DGZImp.Core.Extensions.AutofacManager;
using ATkg.BizAppProject.DomainModels;
using System.Linq;
using DGZImp.Core.Utilities;
using System.Linq.Expressions;
using DGZImp.Core.Extensions;

using Microsoft.Extensions.DependencyInjection;
using Microsoft.AspNetCore.Http;
using ATkg.BizAppProject.IRepositories;
using DGZImp.Core.Exceptions;
using Newtonsoft.Json.Linq;
using DGZImp.Core.EFDbContext;
using DGZImp.Core.DbSqlSugar;
using System.Globalization;
using System.Data.SqlClient;
//using MySql.Data.MySqlClient;

using MySqlConnector;
using DocumentFormat.OpenXml.Drawing.Charts;
using Newtonsoft.Json.Linq;
using DocumentFormat.OpenXml.Office2016.Drawing.ChartDrawing;
//using System.Data;
using MySql.Data;
using static ATkg.BizAppProject.Services.table_wgjyService;
using Zongsoft.Collections;
using Microsoft.IdentityModel.Tokens;




namespace ATkg.BizAppProject.Services
{
    public partial class material_plan_xieService
    {
        private readonly IHttpContextAccessor _httpContextAccessor;
        private readonly Imaterial_plan_xieRepository _repository;//访问数据库
        public ISqlSugarClient Db = AutofacContainerModule.GetService<ServiceDbContext>()?.SqlSugarClient;
        public AmesSyncService ames = AutofacContainerModule.GetService<AmesSyncService>();

        [ActivatorUtilitiesConstructor]
        public material_plan_xieService(
            Imaterial_plan_xieRepository dbRepository,
            IHttpContextAccessor httpContextAccessor
            )
        : base(dbRepository)
        {
            _httpContextAccessor = httpContextAccessor;
            _repository = dbRepository;
            //多租户会用到这init代码，其他情况可以不用
            //base.Init(dbRepository);
        }
        [SugarTable("material_plan_xie")] // 映射表名
        public class MaterialPlan
        {
            [SugarColumn(IsPrimaryKey = true)] // 主键标识（若存在）
            public string schedule_id { get; set; }
            public string steelgrade_id { get; set; }
            public decimal product_qty { get; set; }
            public decimal InputQty_qp { get; set; }
            public decimal Qty_qp { get; set; }
            public decimal InputQty_yl { get; set; }
            public decimal Qty_yl { get; set; }
            public decimal InputQty_qlm { get; set; }
            public decimal Qty_qlm { get; set; }
            public decimal InputQty_yx { get; set; }
            public decimal Qty_yx { get; set; }
            public decimal InputQty_sj { get; set; }
            public decimal Qty_sj { get; set; }
            public DateTime update_data { get; set; }
            public DateTime ModifyTime { get; set; }
            public string done_no { get; set; }
            public string device_type { get; set; }
            public string mold_id { get; set; }
            public string mixed_material_name { get; set; }
            public string bate { get; set; }
            public string mixed_material_weight { get; set; }
        }

        [SugarTable("material_plan_xie_plan")] // 映射表名
        public class material_plan_xie_plan
        {
            [SugarColumn(IsPrimaryKey = true)] // 主键标识（若存在）
            public string schedule_id { get; set; }

            public int yl_dunring { get; set; }
            public string color { get; set; }
            public int yx_device { get; set; }

        }
        public async Task<object> get_info_from_bfmes()
        {
            DateTime now = DateTime.Now;
            string formattedTime = now.ToString("yyyy-MM-dd HH:mm:ss");
            // 安全转换（不抛异常）
            if (DateTime.TryParseExact(
                formattedTime,
                "yyyy-MM-dd HH:mm:ss",
                CultureInfo.InvariantCulture, // 忽略区域差异
                DateTimeStyles.None,
                out DateTime result_date))
            {
                Console.WriteLine($"转换成功: {result_date}");
            }
            else
            {
                Console.WriteLine("格式错误！");
            }
            Console.WriteLine(formattedTime); // 输出示例：2025-06-17 14:30:45
            //await Db.DoDeleteAsync<material_plan_xie>(x => x.CreateId >= 0, true);
            Console.WriteLine("进来了！！！");
            ames.userName = "duyang@atmcn.com";
            ames.password = "Antai@2025";
            ames.url = "http://10.16.12.80/jsonrpc";
            ames.db = "bt";
            //var isSingle = taskNo.IsValuable();
            //Console.WriteLine(taskNo);
            //var typeArray = new[] { "final" };

            var qDomain = new List<object> {

                new List<object> { "production_type", "=", "final" }
            };

            var qFields = new List<string> {
                "id",
                "raw_lot_id",
                "product_id",
                "prodcut_spec",
                "grade",
                "raw_resume_stock_qty",
                "partner_id"
            };
            var qPage = new
            {
                limit = 10000,
                offset = 0,
                order = "name desc",
            };
            // 1. 构建domain条件树
            var domain1 = new List<object>
            {
                "&", "&",
                new List<object> { "workshop_type", "=", "material" },
                new List<object> { "state", "!=", "draft" },
                "&",
                new List<object> { "supply_strategy","=", "outsourcing" },
                "&",
                new List<object> { "schedule_state", "not in", new List<object> { "draft", "cancel", "pause" } },
                new List<object> { "state", "in", new List<object> { "ready", "confirmed", "in_production" } }
            };

            // 2. 构建specification字段映射
            var specification = new Dictionary<string, object>
            {
                {
                    "schedule_id", new Dictionary<string, object>
                    {
                        { "fields", new Dictionary<string, object> { { "display_name", new Dictionary<string, object>() } } }
                    }
                },
                {
                    "top_id", new Dictionary<string, object>
                    {
                        { "fields", new Dictionary<string, object> { { "display_name", new Dictionary<string, object>() } } }
                    }
                },
                {
                    "grade", new Dictionary<string, object>
                    {
                        { "fields", new Dictionary<string, object> { { "display_name", new Dictionary<string, object>() } } }
                    }
                },
                { "schedule_blank_spec", new Dictionary<string, object>() },
                {
                    "mold_id", new Dictionary<string, object>
                    {
                        { "fields", new Dictionary<string, object> { { "display_name", new Dictionary<string, object>() } } }
                    }
                },
                {
                    "steelgrade_id", new Dictionary<string, object>
                    {
                        { "fields", new Dictionary<string, object> { { "display_name", new Dictionary<string, object>() } } }
                    }
                },
                { "date_first_batch", new Dictionary<string, object>() },
                { "date_finished", new Dictionary<string, object>() },
                { "product_qty", new Dictionary<string, object>() },
                { "product_done_stock_accum_qty", new Dictionary<string, object>() }
            };

            // 3. 组合最终结构
            var result = new Dictionary<string, object>
            {
                { "domain", domain1 },
                { "specification", specification }
            };

            var resp = await ames.Get_web_search_read("mps.schedule.line", result);
            if (resp.ContainsKey("error"))
            {
                var message = $"【拉取单据】{resp["error"].ToString()}";
                throw new AppException(message);
            }
            var record = (JArray)resp["result"]["records"];


            var final_data_info_ = new List<object>();

            for (int i = 0; i < record.Count; i++)
            {
                var final_data = new Dictionary<string, object> { };
                int id_sche = (int)record[i]["schedule_id"]["id"];
                var resp_wt = await ames.Get_web_read("mps.schedule", id_sche);
                decimal per_weight_ = (decimal)resp_wt["result"][0]["weight"];
                decimal per_weight = Math.Round(per_weight_, 4);


                //查询冶炼
                // 1. 构建domain条件树（查询筛选条件） 
                var domain_yl = new List<object>
                {
                    "&", // AND逻辑运算符
                    new List<object> { "production_type", "=", "alloy" }, // 三元组条件
                    "&", // 嵌套AND运算符
                    new List<object> { "schedule_id", "ilike", record[i]["schedule_id"]["display_name"] }, // 字符串匹配条件
                    new List<object> { "state", "!=", "cancel" }, // 包含列表值的条件
                };

                // 2. 构建specification字段映射规范
                var specification_yl = new Dictionary<string, object>
                {
                    { "produced_qty", new Dictionary<string, object>() }, // 空配置字段
                    { "product_qty", new Dictionary<string, object>() }          // 空配置字段
                };

                // 3. 组合最终结构
                var result_yl = new Dictionary<string, object>
                {
                    { "domain", domain_yl },
                    { "specification", specification_yl }
                };
                var resp_yl = await ames.Get_web_search_read("mrp.production", result_yl);
                //Console.WriteLine(resp_yl);

                var record_yl = (JArray)resp_yl["result"]["records"];
                decimal InputQty_yl = 0.0m;
                decimal Qty_yl = 0.0m;
                for (int y = 0; y < record_yl.Count; y++)
                {
                    InputQty_yl += (decimal)record_yl[y]["produced_qty"];
                    Qty_yl += (decimal)record_yl[y]["product_qty"];
                }

                // 查询氢破粉
                // 1. 构建domain条件树（查询筛选条件）
                var domain_qp = new List<object>
                {
                    "&", // AND逻辑运算符
                    new List<object> { "production_type", "=", "powder" }, // 三元组条件
                    "&", // 嵌套AND运算符
                    new List<object> { "product_id.atm_type","=", "powder1" },
                    "&",
                    new List<object> { "schedule_id", "ilike", record[i]["schedule_id"]["display_name"] }, // 字符串匹配条件
                    new List<object> { "state", "!=", "cancel" }, // 包含列表值的条件
                };

                // 2. 构建specification字段映射规范
                var specification_qp = new Dictionary<string, object>
                {
                    { "produced_qty", new Dictionary<string, object>() }, // 空配置字段
                    { "product_qty", new Dictionary<string, object>() }          // 空配置字段
                };

                // 3. 组合最终结构
                var result_qp = new Dictionary<string, object>
                {
                    { "domain", domain_qp },
                    { "specification", specification_qp }
                };
                var resp_qp = await ames.Get_web_search_read("mrp.production", result_qp);
                //Console.WriteLine(resp_qp);
                var record_qp = (JArray)resp_qp["result"]["records"];
                decimal InputQty_qp = 0.0m;
                decimal Qty_qp = 0.0m;
                for (int y = 0; y < record_qp.Count; y++)
                {
                    InputQty_qp += (decimal)record_qp[y]["produced_qty"];
                    Qty_qp += (decimal)record_qp[y]["product_qty"];
                }


                // 查询气流磨
                // 1. 构建domain条件树（查询筛选条件）
                var domain_qlm = new List<object>
                {
                    "&", // AND逻辑运算符
                    new List<object> { "production_type", "=", "powder" }, // 三元组条件
                    "&", // 嵌套AND运算符
                    new List<object> { "product_id.atm_type","=", "powder2" },
                    "&",
                    new List<object> { "schedule_id", "ilike", record[i]["schedule_id"]["display_name"] }, // 字符串匹配条件
                    new List<object> { "state", "!=", "cancel"}, // 包含列表值的条件
                };
                // 3. 组合最终结构
                var result_qlm = new Dictionary<string, object>
                {
                    { "domain", domain_qlm },
                    { "specification", specification_qp }
                };
                var resp_qlm = await ames.Get_web_search_read("mrp.production", result_qlm);
                //Console.WriteLine(resp_qlm);
                var record_qlm = (JArray)resp_qlm["result"]["records"];
                decimal InputQty_qlm = 0.0m;
                decimal Qty_qlm = 0.0m;
                for (int y = 0; y < record_qlm.Count; y++)
                {
                    InputQty_qlm += (decimal)record_qlm[y]["produced_qty"];
                    Qty_qlm += (decimal)record_qlm[y]["product_qty"];
                }





                // 查询压型
                // 1. 构建domain条件树（查询筛选条件）
                var domain_yx = new List<object>
                {
                    "&", // AND逻辑运算符
                    new List<object> { "production_type", "=", "blank" }, // 三元组条件
                    "&", // 嵌套AND运算符
                    new List<object> { "product_id.atm_type","=", "press" },
                    "&",
                    new List<object> { "schedule_id", "ilike", record[i]["schedule_id"]["display_name"] }, // 字符串匹配条件
                    new List<object> { "state", "!=", "cancel"}, // 包含列表值的条件
                };
                // 3. 组合最终结构
                var result_yx = new Dictionary<string, object>
                {
                    { "domain", domain_yx },
                    { "specification", specification_qp }
                };
                var resp_yx = await ames.Get_web_search_read("mrp.production", result_yx);
                //Console.WriteLine(resp_qlm);
                var record_yx = (JArray)resp_yx["result"]["records"];
                decimal InputQty_yx = 0.0m;
                decimal Qty_yx = 0.0m;
                for (int y = 0; y < record_yx.Count; y++)
                {
                    InputQty_yx += (decimal)record_yx[y]["produced_qty"];
                    Qty_yx += (decimal)record_yx[y]["product_qty"];
                }


                // 查询烧结
                // 1. 构建domain条件树（查询筛选条件）
                var domain_sj = new List<object>
                {
                    "&", // AND逻辑运算符
                    new List<object> { "production_type", "=", "blank" }, // 三元组条件
                    "&", // 嵌套AND运算符
                    new List<object> { "product_id.atm_type","=", "blank" },
                    "&",
                    new List<object> { "schedule_id", "ilike", record[i]["schedule_id"]["display_name"] }, // 字符串匹配条件
                    new List<object> { "state", "!=", "cancel"}, // 包含列表值的条件
                };
                // 3. 组合最终结构
                var result_sj = new Dictionary<string, object>
                {
                    { "domain", domain_sj },
                    { "specification", specification_qp }
                };
                var resp_sj = await ames.Get_web_search_read("mrp.production", result_sj);
                //Console.WriteLine(resp_qlm);
                var record_sj = (JArray)resp_sj["result"]["records"];
                decimal InputQty_sj = 0.0m;
                decimal Qty_sj = 0.0m;
                for (int y = 0; y < record_sj.Count; y++)
                {
                    InputQty_sj += (decimal)record_sj[y]["produced_qty"];
                    Qty_sj += (decimal)record_sj[y]["product_qty"];
                }
                var done_state = "";
                if (Qty_sj >= (decimal)record[i]["product_qty"])    //判断烧结已派工数量是否大于计划数量  若大于，判断
                {
                    done_state = "已完成";
                }
                else
                {
                    done_state = "否";

                }
                Console.WriteLine("JJJJJJJJJJJJJJJJJJJJJJJJJJ");
                Console.WriteLine(Qty_sj);
                Console.WriteLine((decimal)record[i]["product_qty"]);
                Console.WriteLine((string)record[i]["schedule_id"]["display_name"]);
                Console.WriteLine("LLLLLLLLLLLLLLLLLLLLLLLLLL");
                string mold_id_name = "";
                string device_type = "";
                
                try
                {
                    mold_id_name = (string)record[i]["mold_id"]["display_name"];
                    // 查询烧结
                    // 1. 构建domain条件树（查询筛选条件）
                    var domain_mj = new List<object>
                    {
                        new List<object> { "name", "ilike", mold_id_name }, // 字符串匹配条件
                    };
                    // 2. 构建specification字段映射规范
                    var specification_mj = new Dictionary<string, object>
                    {
                        {
                            "press_id", new Dictionary<string, object>
                            {
                                { "fields", new Dictionary<string, object> { { "display_name", new Dictionary<string, object>() } } }
                            }
                        }        // 空配置字段
                    };
                    // 3. 组合最终结构
                    var result_mj = new Dictionary<string, object>
                    {
                        { "domain", domain_mj },
                        { "specification", specification_mj }
                    };
                    var resp_mj = await ames.Get_web_search_read("atm.plm.mold", result_mj);
                    //Console.WriteLine(resp_qlm);
                    var record_mj = (JArray)resp_mj["result"]["records"];
                    string type_de = (string)record_mj[0]["press_id"]["display_name"];
                    Console.WriteLine("dddddddddddddddddd");
                    Console.WriteLine(type_de);
                    Console.WriteLine("dddddddddddddddddd");
                    if (type_de == "自动压机")
                    {
                        device_type = "全";
                    }
                    else
                    {
                        device_type = "半";
                    }
                    


                }
                catch
                {
                    mold_id_name = "";
                    device_type = "";
                }

                var steelgrade_id = record[i]["steelgrade_id"]["display_name"];
                var domain_gh = new List<object>
                    {
                        new List<object> { "name", "ilike", steelgrade_id }, // 字符串匹配条件
                    };
                // 2. 构建specification字段映射规范
                var specification_gh = new Dictionary<string, object>
                    {
                        {
                            "id", new Dictionary<string, object>{}

                        },        // 空配置字段
                        {
                        "material_ids", new Dictionary<string, object>
                            {
                                { "fields",new Dictionary<string, object>
                                    {
                                        {"product_product_id" ,new Dictionary<string, object>
                                            {
                                                { "fields", new Dictionary<string, object>(){ { "display_name", new Dictionary<string, object>() } } }
                                            }
                                        },
                                        {"percent" ,new Dictionary<string, object> { } },

                                        {"alloy_percent" ,new Dictionary<string, object> { } }
                                    }
                                }
                            }
                        }

                    };
                // 3. 组合最终结构
                var result_gh = new Dictionary<string, object>
                    {
                        { "domain", domain_gh },
                        { "specification", specification_gh }
                    };
                var resp_gh = await ames.Get_web_search_read("atm.product.steelgrade", result_gh);
                Console.WriteLine("7777777777777777");
                Console.WriteLine(resp_gh);
                var record_gh = (JArray)resp_gh["result"]["records"];
                int id_gh = (int)record_gh[0]["id"];
                var material_ids = (JArray)record_gh[0]["material_ids"];
                var mixed_material_name = "";
                double bate_ = 0;
                var bate = "";
                double mixed_material_weight = 0;
                for (int ji = 0; ji < material_ids.Count; ji++)
                {
                    var product_product_id = material_ids[ji]["product_product_id"];
                    var name_ = (string)product_product_id["display_name"];
                    if (name_.Contains("合金"))
                    {
                        mixed_material_name = name_;
                        bate_ = (double)material_ids[ji]["alloy_percent"];
                        bate = bate_.ToString();
                        mixed_material_weight = bate_ * ((double)per_weight * (double)record[i]["product_qty"] / 1000) /100;
                        Console.WriteLine(mixed_material_weight);
                    }
                }
                //var mixed_material_name = material_ids;
                Console.WriteLine("7777777777777777");
                //var specification_gz = new Dictionary<string, object>
                //    {
                //        {
                //            "material_ids", new Dictionary<string, object>
                //            {
                //                { "fields",new Dictionary<string, object>
                //                    {
                //                        {"product_product_id" ,new Dictionary<string, object> 
                //                            { 
                //                                { "fields", new Dictionary<string, object>(){ { "display_name", new Dictionary<string, object>() } } } 
                //                            }
                //                        },
                //                        {"percent" ,new Dictionary<string, object> { } }
                //                    }
                //                }
                //            }
                //        }        // 空配置字段
                //    };
                //var result_gz = new Dictionary<string, object>
                //    {
                //        { "specification", specification_gz }
                //    };
                //Console.WriteLine("这是钢种的ID，看看对不对·····");
                //Console.WriteLine(id_gh);
                //Console.WriteLine("这是钢种的ID，看看对不对·····");

                //var gangzhong = await ames.Get_web_read_all("atm.product.steelgrade", id_gh, result_gz);
                //Console.WriteLine("*************************************************");
                //var record_gz = (JArray)gangzhong["result"];
                //Console.WriteLine(record_gz);
                //Console.WriteLine("*************************************************");
                //var record_gz = (JArray)gangzhong["result"];
                //Console.WriteLine(record_gz);
                //var mixed_material_name = 
                final_data = new Dictionary<string, object>
                    {
                        { "schedule_id", record[i]["schedule_id"]["display_name"] }, // 空配置字段
                        {"done_no",done_state },
                        { "top_id", record[i]["top_id"]["display_name"] },          // 空配置字段, // 空配置字段
                        { "grade", record[i]["grade"]["display_name"] },          // 空配置字段, // 空配置字段
                        { "schedule_blank_spec", record[i]["schedule_blank_spec"] },          // 空配置字段, // 空配置字段
                        { "mold_id", mold_id_name},          // 空配置字段, // 空配置字段
                        { "steelgrade_id", record[i]["steelgrade_id"]["display_name"] },          // 空配置字段, // 空配置字段
                        {"mixed_material_name",mixed_material_name },
                        { "bate",bate},
                        {"mixed_material_weight",Math.Round(mixed_material_weight,2).ToString() },
                        { "date_first_batch", record[i]["date_first_batch"] },          // 空配置字段, // 空配置字段
                        { "date_finished", record[i]["date_finished"] },          // 空配置字段, // 空配置字段
                        { "product_qty", record[i]["product_qty"] },          // 空配置字段          // 空配置字段, // 空配置字段
                        { "per_weight", per_weight },          // 空配置字段
                        { "total_weight",(decimal)per_weight * (decimal)record[i]["product_qty"] /1000 },
                        {"device_type",device_type },
                        { "Qty_yl",Qty_yl },
                        { "InputQty_yl",InputQty_yl },
                        { "Qty_qp",Qty_qp },
                        { "InputQty_qp",InputQty_qp },
                        { "Qty_qlm",Qty_qlm },
                        { "InputQty_qlm",InputQty_qlm },
                        { "Qty_yx",Qty_yx },
                        { "InputQty_yx",InputQty_yx },
                        { "Qty_sj",Qty_sj },
                        { "InputQty_sj",InputQty_sj },
                        { "update_data",result_date },
                    };
                final_data_info_.Add(final_data);

                var final_data_info = new List<material_plan_xie>();
                final_data_info.Add(new material_plan_xie
                {

                    schedule_id = (string)record[i]["schedule_id"]["display_name"],
                    done_no = done_state,
                    top_id = (string)record[i]["top_id"]["display_name"],
                    grade = (string)record[i]["grade"]["display_name"],
                    schedule_blank_spec = (string)record[i]["schedule_blank_spec"],
                    mold_id = mold_id_name,
                    steelgrade_id = (string)record[i]["steelgrade_id"]["display_name"],
                    mixed_material_name = mixed_material_name,
                    bate = bate,
                    mixed_material_weight = Math.Round(mixed_material_weight,2).ToString(),
                    date_first_batch = (DateTime?)record[i]["date_first_batch"],
                    date_finished = (DateTime?)record[i]["date_finished"],
                    product_qty = (decimal)record[i]["product_qty"],
                    per_weight = (decimal)per_weight,
                    total_weight = (decimal)per_weight * (decimal)record[i]["product_qty"] / 1000,
                    device_type = device_type,
                    Qty_yl = Qty_yl,
                    InputQty_yl = InputQty_yl,
                    Qty_qp = Qty_qp,
                    InputQty_qp = InputQty_qp,
                    Qty_qlm = Qty_qlm,
                    InputQty_qlm = InputQty_qlm,
                    Qty_yx = Qty_yx,
                    InputQty_yx = InputQty_yx,
                    Qty_sj = Qty_sj,
                    InputQty_sj = InputQty_sj,
                    update_data = result_date,
                });
                var find_data = Db.Queryable<material_plan_xie>()
                .Where(mp => mp.schedule_id == (string)record[i]["schedule_id"]["display_name"])
                .ToList();
                var re = find_data.Count;
                if (re > 0)
                {
                    int rowsAffected = Db.Updateable<MaterialPlan>()
                    .SetColumns(it => new MaterialPlan()
                    {
                        steelgrade_id = (string)record[i]["steelgrade_id"]["display_name"],
                        mixed_material_name = mixed_material_name,
                        bate = bate,
                        mixed_material_weight = Math.Round(mixed_material_weight,2).ToString(),
                        product_qty = (decimal)record[i]["product_qty"],
                        InputQty_yl = InputQty_yl,  // 更新字段1
                        Qty_yl = Qty_yl,           // 更新字段2
                        InputQty_qp = InputQty_qp,  // 更新字段1
                        Qty_qp = Qty_qp,           // 更新字段2
                        InputQty_qlm = InputQty_qlm,  // 更新字段1
                        Qty_qlm = Qty_qlm,           // 更新字段2
                        InputQty_yx = InputQty_yx,  // 更新字段1
                        Qty_yx = Qty_yx,           // 更新字段2
                        InputQty_sj = InputQty_sj,  // 更新字段1
                        Qty_sj = Qty_sj,           // 更新字段2
                        update_data = result_date,
                        ModifyTime = result_date,
                        done_no = done_state,
                        device_type = device_type,
                        mold_id = mold_id_name

                    })
                    .Where(it => it.schedule_id == (string)record[i]["schedule_id"]["display_name"]) // 精确条件
                    .ExecuteCommand();
                }
                else
                {
                    await Db.DoInsertAsync<material_plan_xie>(final_data_info);
                }
            }
            return final_data_info_;
        }



        public void update_devices(string schedule_id,string devices_type)
        {
            Console.WriteLine("进来了！！");
            // 查询数据库中当天最大的code
            // 使用 SqlSugar 的 Queryable 语法
            var result = Db.Queryable<material_plan_xie>()  //  
                .Select(m => m.update_data)               // 选择 update_data 字段
                .Take(1)                                 // 限制返回 1 条记录
                .ToList();                               // 执行查询并返回列表
            int rowsAffected = Db.Updateable<MaterialPlan>()
                    .SetColumns(it => new MaterialPlan()
                    {
                        device_type = devices_type,
                    })
                    .Where(it => it.schedule_id == schedule_id) // 精确条件
                    .ExecuteCommand();
         
        }

        public async Task<object> get_db_data()
        {
            Console.WriteLine("进来了！！");
            // 查询数据库中当天最大的code
            // 使用 SqlSugar 的 Queryable 语法
            var result = Db.Queryable<material_plan_xie>()  //  
                .Select(m => m.update_data)               // 选择 update_data 字段
                //.Take(1)                                 // 限制返回 1 条记录
                .ToList();                               // 执行查询并返回列表
            return result;
        }

        public async Task<object> get_db_data_compute()
        {
            Console.WriteLine("进来了！！");
            // 查询数据库中当天最大的code
            // 使用 SqlSugar 的 Queryable 语法
            var result = Db.Queryable<material_plan_xie>()  //  
                .Select(m => m.update_data)               // 选择 update_data 字段
                //.Take(1)                                 // 限制返回 1 条记录
                .ToList();                               // 执行查询并返回列表
            return result;
        }

        public async Task<object> get_db_data_order_compute()
        {
            Console.WriteLine("进来了！！");
            // 查询数据库中当天最大的code
            // 使用 SqlSugar 的 Queryable 语法
            var result = Db.Queryable<material_plan_xie>()  //  
                .Where(m => m.IsValid == 1)
                .Select(m => new
                {
                    m.schedule_id,
                    m.top_id,
                    m.grade,
                    m.schedule_blank_spec,
                    m.mold_id,
                    m.steelgrade_id,
                    m.product_qty,
                    m.per_weight,
                    m.total_weight,
                    m.device_type,
                    m.date_first_batch,
                    m.Qty_yl,
                    m.InputQty_yl,
                    m.Qty_qp,
                    m.InputQty_qp,
                    m.Qty_qlm,
                    m.InputQty_qlm,
                    m.Qty_yx,
                    m.InputQty_yx,
                    m.Qty_sj,
                    m.InputQty_sj,
                })               // 选择 update_data 字段
                                 //.Take(1)                                 // 限制返回 1 条记录
                .ToList();                               // 执行查询并返回列表

            string sql = @"SELECT * FROM `material_plan_xie_plan` WHERE schedule_id in (@scheduleIds)";
            //var a = Db.
            var res2 = Db.Ado.SqlQuery<object>(sql, new List<SugarParameter>() {
                new SugarParameter("@scheduleIds", result.Select(x=>x.schedule_id).ToArray())
            });

            Console.WriteLine(result[0]);
            var final_dd = new List<object>();
            for (int i = 0; i < result.Count; i++)
            {
                dynamic reader = res2.Where(x => ((dynamic)x).schedule_id == result[i].schedule_id).FirstOrDefault();
                JObject jsonObj = JObject.FromObject(result[i]);
                if (reader != null)
                {
                    Console.WriteLine(reader.schedule_id); // 替换为实际字段名                                                                          // 将对象转为 JObject

                    jsonObj.Add("yl_startdate", reader.yl_startdate != null ? (DateTime)reader.yl_startdate:"");
                    jsonObj.Add("yl_dunring", reader.yl_dunring != null ? (reader.yl_dunring is long l ? Convert.ToInt32(l) : (int)reader.yl_dunring):"");
                    jsonObj.Add("yl_per_in", reader.yl_per_in != null ? (reader.yl_per_in is long l1 ? Convert.ToInt32(l1) : (int)reader.yl_per_in) : "");
                    jsonObj.Add("qp_startdate", reader.qp_startdate != null ? (DateTime)reader.qp_startdate : "");
                    jsonObj.Add("qp_dunring", reader.qp_dunring != null ? (reader.qp_dunring is long l2 ? Convert.ToInt32(l2) : (int)reader.qp_dunring) : "");
                    jsonObj.Add("qp_per_in", reader.qp_per_in != null ? (reader.qp_per_in is long l3 ? Convert.ToInt32(l3) : (int)reader.qp_per_in) : "");
                    jsonObj.Add("qlm_startdate", reader.qlm_startdate != null ? (DateTime)reader.qlm_startdate : "");
                    jsonObj.Add("qlm_dunring", reader.qlm_dunring != null ? (reader.qlm_dunring is long l4 ? Convert.ToInt32(l4) : (int)reader.qlm_dunring) : "");
                    jsonObj.Add("qlm_per_in", reader.qlm_per_in != null ? (reader.qlm_per_in is long l41 ? Convert.ToInt32(l41) : (int)reader.qlm_per_in) : "");
                    jsonObj.Add("yx_startdate", reader.yx_startdate != null ? (DateTime)reader.yx_startdate : "");
                    jsonObj.Add("yx_dunring", reader.yx_dunring != null ? (reader.yx_dunring is long l5 ? Convert.ToInt32(l5) : (int)reader.yx_dunring) : "");
                    jsonObj.Add("yx_per_in", reader.yx_per_in != null ? (reader.yx_per_in is long l6 ? Convert.ToInt32(l6) : (int)reader.yx_per_in) : "");
                    jsonObj.Add("sj_startdate", reader.sj_startdate != null ? (DateTime)reader.sj_startdate : "");
                    jsonObj.Add("sj_dunring", reader.sj_dunring != null ? (reader.sj_dunring is long l7 ? Convert.ToInt32(l7) : (int)reader.sj_dunring) : "");
                    jsonObj.Add("sj_per_in", reader.sj_per_in != null ? (reader.sj_per_in is long l8 ? Convert.ToInt32(l8) : (int)reader.sj_per_in) : "");

                }
                else
                {
                    jsonObj.Add("yl_startdate", "");
                    jsonObj.Add("yl_dunring", "");
                    jsonObj.Add("yl_per_in", "");
                    jsonObj.Add("qp_startdate", "");
                    jsonObj.Add("qp_dunring", "");
                    jsonObj.Add("qp_per_in", "");
                    jsonObj.Add("qlm_startdate", "");
                    jsonObj.Add("qlm_dunring", "");
                    jsonObj.Add("qlm_per_in", "");
                    jsonObj.Add("yx_startdate", "");
                    jsonObj.Add("yx_dunring", "");
                    jsonObj.Add("yx_per_in", "");
                    jsonObj.Add("sj_startdate", "");
                    jsonObj.Add("sj_dunring", "");
                    jsonObj.Add("sj_per_in", "");
                }
                final_dd.Add(jsonObj);
            }


            return final_dd;
        }


        public async Task<object> get_db_data_order()
        {
            Console.WriteLine("进来了！！");
            // 查询数据库中当天最大的code
            // 使用 SqlSugar 的 Queryable 语法
            var result = Db.Queryable<material_plan_xie>()  //  
                .Where(m => m.IsValid == 1)
                .Select(m => new
                {
                    m.schedule_id,
                    m.top_id,
                    m.grade,
                    m.schedule_blank_spec,
                    m.mold_id,
                    m.steelgrade_id,
                    m.product_qty,
                    m.per_weight,
                    m.total_weight,
                    m.device_type,
                    m.date_first_batch,
                    m.InputQty_yx
                })               // 选择 update_data 字段
                                 //.Take(1)                                 // 限制返回 1 条记录
                .ToList();                               // 执行查询并返回列表

            string sql = @"SELECT * FROM `material_plan_xie_plan` WHERE schedule_id in (@scheduleIds)";
            var res2 = Db.Ado.SqlQuery<object>(sql, new List<SugarParameter>() {
                new SugarParameter("@scheduleIds", result.Select(x=>x.schedule_id).ToArray())
            });

            Console.WriteLine(result[0]);
            var final_dd = new List<object>();
            for (int i = 0; i < result.Count; i++)
            {
                dynamic reader = res2.Where(x => ((dynamic)x).schedule_id == result[i].schedule_id).FirstOrDefault();
                JObject jsonObj = JObject.FromObject(result[i]);
                if (reader != null)
                {
                    Console.WriteLine(reader.schedule_id); // 替换为实际字段名             InputQty_yx                                                             // 将对象转为 JObject

                    jsonObj.Add("yl_startdate", reader.yl_startdate != null ? (DateTime)reader.yl_startdate : "");
                    jsonObj.Add("yl_dunring", reader.yl_dunring != null ?( reader.yl_dunring is long l ? Convert.ToInt32(l) : (int)reader.yl_dunring):"");
                    jsonObj.Add("yl_per_in", reader.yl_per_in != null ? (reader.yl_per_in is long l1 ? Convert.ToInt32(l1) : (int)reader.yl_per_in) : "");
                    jsonObj.Add("qp_startdate", reader.qp_startdate != null ? (DateTime)reader.qp_startdate : "");
                    jsonObj.Add("qp_dunring", reader.qp_dunring != null ? (reader.qp_dunring is long l2 ? Convert.ToInt32(l2) : (int)reader.qp_dunring) : "");
                    jsonObj.Add("qp_per_in", reader.qp_per_in != null ? (reader.qp_per_in is long l3 ? Convert.ToInt32(l3) : (int)reader.qp_per_in) : "");
                    jsonObj.Add("qlm_startdate", reader.qlm_startdate != null ? (DateTime)reader.qlm_startdate : "");
                    jsonObj.Add("qlm_dunring", reader.qlm_dunring != null ? (reader.qlm_dunring is long l4 ? Convert.ToInt32(l4) : (int)reader.qlm_dunring) : "");
                    jsonObj.Add("qlm_per_in", reader.qlm_per_in != null ? (reader.qlm_per_in is long l41 ? Convert.ToInt32(l41) : (int)reader.qlm_per_in) : "");
                    jsonObj.Add("yx_startdate", reader.yx_startdate != null ? (DateTime)reader.yx_startdate : "");
                    jsonObj.Add("yx_dunring", reader.yx_dunring != null ? (reader.yx_dunring is long l5 ? Convert.ToInt32(l5) : (int)reader.yx_dunring) : "");
                    jsonObj.Add("yx_per_in", reader.yx_per_in != null ? (reader.yx_per_in is long l6 ? Convert.ToInt32(l6) : (int)reader.yx_per_in) : "");
                    jsonObj.Add("yx_device", reader.yx_device != null ? (reader.yx_device is long l61 ? Convert.ToInt32(l61) : (int)reader.yx_device) : "");
                    jsonObj.Add("sj_startdate", reader.sj_startdate != null ? (DateTime)reader.sj_startdate : "");
                    jsonObj.Add("sj_dunring", reader.sj_dunring != null ? (reader.sj_dunring is long l7 ? Convert.ToInt32(l7) : (int)reader.sj_dunring) : "");
                    jsonObj.Add("sj_per_in", reader.sj_per_in != null ? (reader.sj_per_in is long l8 ? Convert.ToInt32(l8) : (int)reader.sj_per_in) : "");
                    jsonObj.Add("color", reader.color != null ? (string)reader.color : "");
                    //jsonObj.Add("InputQty_yx", result[i].InputQty_yx);

                }
                else
                {
                    jsonObj.Add("yl_startdate", "");
                    jsonObj.Add("yl_dunring", "");
                    jsonObj.Add("yl_per_in", "");
                    jsonObj.Add("qp_startdate", "");
                    jsonObj.Add("qp_dunring", "");
                    jsonObj.Add("qp_per_in", "");
                    jsonObj.Add("qlm_startdate", "");
                    jsonObj.Add("qlm_dunring", "");
                    jsonObj.Add("qlm_per_in", "");
                    jsonObj.Add("yx_startdate", "");
                    jsonObj.Add("yx_dunring", "");
                    jsonObj.Add("yx_per_in", "");
                    jsonObj.Add("yx_device", "");
                    jsonObj.Add("sj_startdate", "");
                    jsonObj.Add("sj_dunring", "");
                    jsonObj.Add("sj_per_in", "");
                    jsonObj.Add("color", "");
                    //jsonObj.Add("InputQty_yx", ""); 
                }
                final_dd.Add(jsonObj);
            }


            return final_dd;
        }
       
        public class MaterialPlanUpdater1
        {
            public string UpsertData(JObject plan_data_final)
            {
                //Console.WriteLine(scheduleId, startDate, dunring, stopDate);

                //"ServiceDbContext": "Server=localhost;Port=3306;Database=biz_app;Uid=root;Pwd=admin; AllowLoadLocalInfile=true;",
                string connectionString = "Server=10.16.12.72;Port=3306;Database=biz_app;Uid=root;Pwd=fastbee;";
                //string connectionString = "Server=localhost;Port=3306;Database=biz_app;Uid=root;Pwd=fastbee;";
                Console.WriteLine("KKKKKKKKKKKKK");
                Console.WriteLine((string)plan_data_final["db_type"]);
                if ((string)plan_data_final["db_type"] == "保存")
                {
                    using (var connection = new MySqlConnection(connectionString))
                    {
                        connection.Open();

                        // 使用 ON DUPLICATE KEY UPDATE 实现原子操作
                        string upsertSql = @"
                INSERT INTO material_plan_xie_plan 
                    (schedule_id, yl_startdate, yl_dunring, yl_per_in, qp_startdate, qp_dunring, qp_per_in, qlm_startdate, qlm_dunring, qlm_per_in
                    , yx_startdate, yx_dunring, yx_per_in, yx_device, sj_startdate, sj_dunring, sj_per_in)
                VALUES 
                    (@scheduleId, @ylstart, @yldunring, @ylperIn, @qpstart, @qpdunring, @qpperIn, @qlmstart, @qlmdunring, @qlmperIn
                    , @yxstart, @yxdunring, @yxperIn, @yxDevice, @sjstart, @sjdunring, @sjperIn)
                ON DUPLICATE KEY UPDATE
                    yl_startdate = VALUES(yl_startdate),
                    yl_dunring = VALUES(yl_dunring),
                    yl_per_in = VALUES(yl_per_in),
                    qp_startdate = VALUES(qp_startdate),
                    qp_dunring = VALUES(qp_dunring),
                    qp_per_in = VALUES(qp_per_in),
                    qlm_startdate = VALUES(qlm_startdate),
                    qlm_dunring = VALUES(qlm_dunring),
                    qlm_per_in = VALUES(qlm_per_in),
                    yx_startdate = VALUES(yx_startdate),
                    yx_dunring = VALUES(yx_dunring),
                    yx_per_in = VALUES(yx_per_in),
                    yx_device = VALUES(yx_device),
                    sj_startdate = VALUES(sj_startdate),
                    sj_dunring = VALUES(sj_dunring),
                    sj_per_in = VALUES(sj_per_in)                
                    ";
                        using (var command = new MySqlCommand(upsertSql, connection))
                        {
                            // 参数化防止 SQL 注入 
                            command.Parameters.AddWithValue("@scheduleId", (string)plan_data_final["schedule_id"]);
                            command.Parameters.AddWithValue("@ylstart", (DateTime)plan_data_final["yl_startdate"]);
                            command.Parameters.AddWithValue("@yldunring", (string)plan_data_final["yl_dunring"] == "" ? null:(int)plan_data_final["yl_dunring"]);
                            command.Parameters.AddWithValue("@ylperIn", (string)plan_data_final["yl_per_in"] == "" ? null : (int)plan_data_final["yl_per_in"]);

                            command.Parameters.AddWithValue("@qpstart", (DateTime)plan_data_final["qp_startdate"]);
                            command.Parameters.AddWithValue("@qpdunring", (string)plan_data_final["qp_dunring"] == "" ? null : (int)plan_data_final["qp_dunring"]);
                            command.Parameters.AddWithValue("@qpperIn", (string)plan_data_final["qp_per_in"] == "" ? null : (int)plan_data_final["qp_per_in"]);

                            command.Parameters.AddWithValue("@qlmstart", (DateTime)plan_data_final["qlm_startdate"]);
                            command.Parameters.AddWithValue("@qlmdunring", (string)plan_data_final["qlm_dunring"] == "" ? null : (int)plan_data_final["qlm_dunring"]);
                            command.Parameters.AddWithValue("@qlmperIn", (string)plan_data_final["qlm_per_in"] == "" ? null : (int)plan_data_final["qlm_per_in"]);

                            command.Parameters.AddWithValue("@yxstart", (DateTime)plan_data_final["yx_startdate"]);
                            command.Parameters.AddWithValue("@yxdunring", (string)plan_data_final["yx_dunring"] == "" ? null : (int)plan_data_final["yx_dunring"]);
                            command.Parameters.AddWithValue("@yxperIn", (string)plan_data_final["yx_per_in"] == "" ? null : (int)plan_data_final["yx_per_in"]);
                            command.Parameters.AddWithValue("@yxDevice", (string)plan_data_final["yx_device"] == "" ? null : (int)plan_data_final["yx_device"]);

                            command.Parameters.AddWithValue("@sjstart", (DateTime)plan_data_final["sj_startdate"]);
                            command.Parameters.AddWithValue("@sjdunring", (string)plan_data_final["sj_dunring"] == "" ? null : (int)plan_data_final["sj_dunring"]);
                            command.Parameters.AddWithValue("@sjperIn", (string)plan_data_final["sj_per_in"] == "" ? null : (int)plan_data_final["sj_per_in"]);

                            int result = command.ExecuteNonQuery();

                            // 根据返回值判断操作类型 device_type
                            string operation = result switch
                            {
                                1 => "插入成功（无冲突）",
                                2 => "更新成功（检测到冲突并更新）",
                                _ => "数据未变化或操作失败"
                            };
                            Console.WriteLine(operation);
                            return operation;
                        }
                    }
                }
                else
                {
                    try
                    {
                        using (MySqlConnection connection = new MySqlConnection(connectionString))
                        {
                            connection.Open();

                            // 定义SQL语句（清空两个字段为NULL）
                            string sql = @"
                                UPDATE material_plan_xie_plan 
                                SET yl_startdate = NULL, 
                                    yl_dunring = NULL, 
                                    yl_per_in = NULL , 
                                    qp_startdate = NULL , 
                                    qp_dunring = NULL , 
                                    qp_per_in = NULL , 
                                    qlm_startdate = NULL , 
                                    qlm_dunring = NULL , 
                                    qlm_per_in = NULL , 
                                    yx_startdate = NULL , 
                                    yx_dunring = NULL , 
                                    yx_per_in = NULL , 
                                    yx_device = NULL , 
                                    sj_startdate = NULL , 
                                    sj_dunring = NULL , 
                                    sj_per_in = NULL 
                                WHERE schedule_id = @scheduleId";

                            using (MySqlCommand command = new MySqlCommand(sql, connection))
                            {
                                // 添加参数（防止SQL注入）
                                command.Parameters.AddWithValue("@scheduleId", (string)plan_data_final["schedule_id"]); // 替换为实际值

                                // 执行更新并获取受影响行数
                                int rowsAffected = command.ExecuteNonQuery();
                                Console.WriteLine($"{rowsAffected} 行数据已更新。");
                                return "清空成功";
                            }
                        }
                    }
                    catch (Exception ex)
                    {
                        Console.WriteLine($"数据库操作失败: {ex.Message}");
                        return ex.Message;
                    }
                }

                
               //update_devices((string)plan_data_final["schedule_id"], (string)plan_data_final["device_type"]);

            }

        }

        public async Task<string> get_db_data_order_plan(JObject plan_data_final)
        {
            Console.WriteLine("进来了！！");
            // 查询数据库中当天最大的code
            // 使用 SqlSugar 的 Queryable 语法
            Console.WriteLine("GGGGGGGGGGGGGG");
            Console.WriteLine(plan_data_final["sj_startdate"]);
            //string connectionString = "server=localhost;port=3306;database=biz_app;user=root;password=admin;";
            //var dgdgd = _config["Interfaces:AnTaiMes:UserName"];
            string connectionString = "Server=10.16.12.72;Port=3306;Database=biz_app;Uid=root;Pwd=fastbee;";
            //string connectionString = "Server=localhost;Port=3306;Database=biz_app;Uid=root;Pwd=fastbee;";
            var final_data_info = new List<object>();
            var updater = new MaterialPlanUpdater1();
            string result_ = updater.UpsertData(plan_data_final);

            return result_;
        }
        public static void QueryJune2025Data(string connectionString)
        {
            // 动态生成时间范围（2025年6月整月）
            DateTime startDate = new DateTime(2025, 6, 1);
            DateTime endDate = startDate.AddMonths(1);

            // 参数化查询语句（使用MySQL的日期格式）
            string query = @"
            SELECT * 
            FROM at_data_energy 
            WHERE dr = @dr 
            AND item1 = @item1 
            AND time1 >= @startDate 
            AND time1 < @endDate";

            try
            {
                using (MySqlConnection connection = new MySqlConnection(connectionString))
                {
                    // 创建带参数的命令对象
                    using (MySqlCommand command = new MySqlCommand(query, connection))
                    {
                        // 添加参数并指定类型
                        command.Parameters.Add(new MySqlParameter("@dr", MySqlDbType.Int32) { Value = 0 });
                        command.Parameters.Add(new MySqlParameter("@item1", MySqlDbType.VarChar, 50) { Value = "安泰稀土" });
                        command.Parameters.Add(new MySqlParameter("@startDate", MySqlDbType.DateTime) { Value = startDate });
                        command.Parameters.Add(new MySqlParameter("@endDate", MySqlDbType.DateTime) { Value = endDate });

                        connection.Open();

                        // 执行查询并读取数据
                        using (MySqlDataReader reader = command.ExecuteReader())
                        {
                            // 动态输出列标题
                            for (int i = 0; i < reader.FieldCount; i++)
                            {
                                Console.Write(reader.GetName(i) + "\t");
                            }
                            Console.WriteLine("\n---------------------------------");

                            // 逐行处理数据
                            while (reader.Read())
                            {
                                // 示例：读取具体字段（根据实际表结构调整）
                                string item1 = reader.GetString("item1");
                                DateTime time1 = reader.GetDateTime("time1");
                                //decimal value = reader.GetDecimal("value");

                                // 格式化输出（时间格式化为yyyy-MM-dd HH:mm:ss）
                                Console.WriteLine($"{item1}\t{time1:yyyy-MM-dd HH:mm:ss}\t");
                            }
                        }
                    }
                }
            }
            catch (MySqlException ex)
            {
                Console.WriteLine($"MySQL错误 [{ex.Number}]: {ex.Message}");
            }
            catch (Exception ex)
            {
                Console.WriteLine($"通用错误: {ex.Message}");
            }
        }

        public static void QueryAtStepData(string connectionString)
        {
            // 参数化查询语句（防止SQL注入）
            string query = @"
            SELECT * 
            FROM at_step 
            WHERE item1 = @item1 
            AND dr = @dr";

            try
            {
                using (MySqlConnection connection = new MySqlConnection(connectionString))
                {
                    // 创建带参数的MySqlCommand对象
                    using (MySqlCommand command = new MySqlCommand(query, connection))
                    {
                        // 添加参数并赋值（自动处理类型转换）
                        command.Parameters.AddWithValue("@item1", "安泰稀土");
                        command.Parameters.AddWithValue("@dr", 0);

                        connection.Open();

                        // 执行查询并读取数据
                        using (MySqlDataReader reader = command.ExecuteReader())
                        {
                            // 动态获取列信息
                            for (int i = 0; i < reader.FieldCount; i++)
                            {
                                Console.Write(reader.GetName(i) + "\t");
                            }
                            Console.WriteLine();

                            // 逐行处理数据
                            while (reader.Read())
                            {
                                // 示例：读取具体字段（根据实际表结构调整）
                                string item1Value = reader.GetString("item1");
                                int drValue = reader.GetInt32("dr");
                                //DateTime createTime = reader.GetDateTime("create_time");

                                // 输出格式化结果
                                Console.WriteLine($"{item1Value}\t{drValue}\t");

                            }
                        }
                    }
                }
            }
            catch (MySqlException ex)
            {
                Console.WriteLine($"MySQL错误 [{ex.Number}]: {ex.Message}");
            }
            catch (Exception ex)
            {
                Console.WriteLine($"通用错误: {ex.Message}");
            }
        }

        public class QueryResult
        {
            public DataTable AtStepData { get; set; }
            public DataTable EnergyData { get; set; }
        }
        public async Task<object> get_db_get_db_eng(string startTime, string endtime)
        {
            Console.WriteLine("进来了！！");
            // 查询数据库中当天最大的code
            // 使用 SqlSugar 的 Queryable 语法
            //string connectionString = "server=localhost;port=3306;database=biz_app;user=root;password=admin;";
            string connectionString = "Server=10.7.4.214;Port=3306;Database=imr_client;Uid=root;Pwd=12345678;";
            var final_data_info = new List<object>();
            //string query = @"
            //SELECT * 
            //FROM at_step 
            //WHERE item1 = @item1 
            //AND dr = @dr";
            ////var updater = new MaterialPlanUpdater1();
            ////updater.UpsertData(plan_data_final);
            //QueryAtStepData(connectionString);
            //QueryJune2025Data(connectionString);

            var result = get_eng(connectionString,"","");

            return result;
        }

        public List<object> get_eng(string connect_string,string startTime,string endtime)
        {
            // 数据库连接字符串（根据实际情况修改）
            string connectionString = connect_string;

            // 构建参数化查询语句
            string query = @"
            SELECT 
                (SELECT name FROM at_region WHERE pk = ad.pk_region) AS region_name,
                (SELECT name FROM at_step WHERE pk = ad.pk_step) AS step_name,
                ad.`name`,
                ade.`vriable_value_now`,
                ade.inputtime 
            FROM at_data_energy ade
            LEFT JOIN at_device ad ON ade.pk_device = ad.pk
            WHERE ade.inputtime >= @startTime
              AND ade.inputtime < @endTime
            ORDER BY ad.name, ade.inputtime"
            ;

            try
            {

                var final_data_info_ = new List<object>();
                using (MySqlConnection connection = new MySqlConnection(connectionString))
                {
                    // 创建命令对象
                    using (MySqlCommand command = new MySqlCommand(query, connection))
                    {
                        // 设置参数值
                        command.Parameters.AddWithValue("@startTime", "2025-06-30 10:00:00");
                        command.Parameters.AddWithValue("@endTime", "2025-06-30 10:30:00");

                        // 打开连接
                        connection.Open();

                        // 执行查询
                        using (MySqlDataReader reader = command.ExecuteReader())
                        {
                            // 输出列标题
                            Console.WriteLine($"{"Region",15} {"Step",10} {"Device",20} {"Value",15} {"Time",20}");

                            var i = 0;
                            // 读取数据
                            while (reader.Read())
                            {
                                // 读取各列数据（注意列名与查询结果对应）
                                string region = reader["region_name"].ToString();
                                string step = reader["step_name"].ToString();
                                string device = reader["name"].ToString();
                                string value = reader["vriable_value_now"].ToString();
                                DateTime time = (DateTime)reader["inputtime"];

                                // 格式化输出
                                Console.WriteLine($"{region,15} {step,10} {device,20} {value,15} {time:yyyy-MM-dd HH:mm:ss,20}");
                                var final_data = new Dictionary<string, object>
                                {
                                    { "region_name", reader["region_name"].ToString() }, // 空配置字段
                                    {"step_name",reader["step_name"].ToString() },
                                    { "name", reader["name"].ToString()},          // 空配置字段, // 空配置字段
                                    { "vriable_value_now", reader["vriable_value_now"].ToString() }
                                };
                                i++;

                                final_data_info_.Add(final_data);
                            }
                            Console.WriteLine($"{i} records");                
                        }
                    }
                }
                return final_data_info_;
            }
            catch (Exception ex)
            {
                Console.WriteLine($"数据库操作异常: {ex.Message}");
                var r = new List<object>();
                var final_data = new Dictionary<string, object>
                { };
                r.Add(
                    final_data
                    );
                return r;
            }
        }

        public async Task<object> get_no_plan_order_detal()
        {
            Console.WriteLine("进来了！！");
            // 查询数据库中当天最大的code
            // 使用 SqlSugar 的 Queryable 语法
            var result = Db.Queryable<material_plan_xie>()  //  
                .Where(m => m.IsValid == 1)
                .Select(m => new
                {
                    m.schedule_id,
                    m.top_id,
                    m.grade,
                    m.schedule_blank_spec,
                    m.mold_id,
                    m.steelgrade_id,
                    m.product_qty,
                    m.per_weight,
                    m.total_weight,
                    m.device_type,
                    m.date_first_batch
                })              
                .ToList();
            Console.WriteLine(result.Count);
            for(int i = 0; i < result.Count; i++)
            {
                Console.WriteLine(result[i]);
            }
            // 1. 提取result中所有不重复的schedule_id，用于批量查询
            var scheduleIds = result.Select(m => m.schedule_id).Distinct().ToList();
            Console.WriteLine(scheduleIds.Count);

            // 2. 批量查询material_plan_xie_plan中相关的记录，构建schedule_id与yl_startdate的映射
            // 处理可能存在的重复schedule_id，这里取第一条记录的yl_startdate
            var planMap = Db.Queryable<material_plan_xie_plan>()
                .Where(p => scheduleIds.Contains(p.schedule_id))
                .Select(p => new { p.schedule_id, p.yl_dunring, p.yx_device })
                .ToList()
                .GroupBy(p => p.schedule_id)
                .ToDictionary(g => g.Key, g => g.First().yx_device);

            // 3. 过滤result集合：
            // - 不在planMap中的记录保留
            // - 在planMap中但yl_startdate为空的记录保留
            // - 在planMap中且yl_startdate不为空的记录移除

            //var filteredResult = result.Where(item =>
            //{
            //    // 检查当前记录的schedule_id是否存在于planMap中
            //    if (planMap.TryGetValue(item.schedule_id, out var yx_device))
            //    {
            //        // 存在则判断yl_startdate是否为空
            //        return yx_device == null;
            //    }
            //    // 不存在则保留
            //    return true;
            //}).ToList();
            //Console.WriteLine(filteredResult.Count);
            //Console.WriteLine(filteredResult);
            // 1. 查询material_plan_xie_plan表中yx_device不为空的schedule_id
            var invalidScheduleIds = Db.Queryable<material_plan_xie_plan>()
                .Where(p => p.yx_device >0) // 假设yx_device是字符串类型
                .Select(p => p.schedule_id)
                .Distinct() // 去重，只保留唯一的schedule_id
                .ToList();
            
            // 2. 从result中移除这些schedule_id对应的记录
            var filteredResult = result.Where(m => !invalidScheduleIds.Contains(m.schedule_id)).ToList();
            return filteredResult;
        }
        public async Task<object> get_no_plan_order_deta2()
        {
            Console.WriteLine("进来了！！");
            // 查询数据库中当天最大的code
            // 使用 SqlSugar 的 Queryable 语法
            var result = Db.Queryable<material_plan_xie>()  //  
                .Where(m => m.IsValid == 1)
                .Select(m => new
                {
                    m.schedule_id,
                    m.top_id,
                    m.grade,
                    m.schedule_blank_spec,
                    m.mold_id,
                    m.steelgrade_id,
                    m.product_qty,
                    m.per_weight,
                    m.total_weight,
                    m.device_type,
                    m.date_first_batch
                })
                .ToList();
            Console.WriteLine(result.Count);
            for (int i = 0; i < result.Count; i++)
            {
                Console.WriteLine(result[i]);
            }
            // 1. 提取result中所有不重复的schedule_id，用于批量查询
            var scheduleIds = result.Select(m => m.schedule_id).Distinct().ToList();
            Console.WriteLine(scheduleIds.Count);

            // 2. 批量查询material_plan_xie_plan中相关的记录，构建schedule_id与yl_startdate的映射
            // 处理可能存在的重复schedule_id，这里取第一条记录的yl_startdate
            var planMap = Db.Queryable<material_plan_xie_plan>()
                .Where(p => scheduleIds.Contains(p.schedule_id))
                .Select(p => new { p.schedule_id, p.yl_dunring, p.yx_device })
                .ToList()
                .GroupBy(p => p.schedule_id)
                .ToDictionary(g => g.Key, g => g.First().yx_device);

            // 3. 过滤result集合：
            // - 不在planMap中的记录保留
            // - 在planMap中但yl_startdate为空的记录保留
            // - 在planMap中且yl_startdate不为空的记录移除

            var filteredResult = result.Where(item =>
            {
                // 检查当前记录的schedule_id是否存在于planMap中
                if (planMap.TryGetValue(item.schedule_id, out var yx_device))
                {
                    // 存在则判断yl_startdate是否为空
                    return yx_device == null;
                }
                // 不存在则保留
                return true;
            }).ToList();
            Console.WriteLine(filteredResult.Count);
            Console.WriteLine(filteredResult);
            return filteredResult;
        }
    }
}
